package com.XG.noteapp

import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.appbar.MaterialToolbar
import com.XG.noteapp.adapter.NoteAdapter
import com.XG.noteapp.data.Note
import com.XG.noteapp.roomsql.AppDatabase
import com.bumptech.glide.Glide
import com.google.android.material.button.MaterialButton
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
import java.util.UUID

class MainActivity : AppCompatActivity() {

    private lateinit var materialToolbar: MaterialToolbar
    private lateinit var recyclerView: RecyclerView
    private lateinit var noteAdapter: NoteAdapter
    private lateinit var addImageButton: MaterialButton
    private var currentImageUri: String? = null
    private lateinit var noteDatabase: AppDatabase

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        // 初始化Toolbar
        materialToolbar = findViewById(R.id.toolbar)
        setSupportActionBar(materialToolbar)
        supportActionBar?.title = "笔记应用"

        // 初始化RecyclerView
        recyclerView = findViewById(R.id.recyclerView)
        recyclerView.layoutManager = LinearLayoutManager(this)

        // 初始化数据库
        noteDatabase = AppDatabase.getInstance(this)

        // 从数据库中加载笔记数据
        lifecycleScope.launch {
            val notes = noteDatabase.noteDao().getAllNotes()
            noteAdapter = NoteAdapter(notes) { note ->
                val intent = Intent(this@MainActivity, DetailActivity::class.java)
                intent.putExtra("note_id", note.id)
                startActivity(intent)
            }
            recyclerView.adapter = noteAdapter
        }

        // 设置ItemTouchHelper以实现滑动删除
        setupItemTouchHelper()
    }

    private fun setupItemTouchHelper() {
        val itemTouchHelperCallback = object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
            override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
                return false // 不支持移动操作
            }

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                val position = viewHolder.adapterPosition
                val note = noteAdapter.notes[position]

                // 显示删除确认对话框
                showDeleteNoteDialog(note)
            }
        }

        val itemTouchHelper = ItemTouchHelper(itemTouchHelperCallback)
        itemTouchHelper.attachToRecyclerView(recyclerView)
    }

    private fun showDeleteNoteDialog(note: Note) {
        val builder = AlertDialog.Builder(this)
            .setTitle("删除笔记")
            .setMessage("确定要删除该笔记吗？")
            .setPositiveButton("删除") { _, _ ->
                deleteNote(note)
            }
            .setNegativeButton("取消", null)
            .create()

        builder.show()
    }

    private fun deleteNote(note: Note) {
        lifecycleScope.launch(Dispatchers.IO) {
            noteDatabase.noteDao().deleteNote(note)

            withContext(Dispatchers.Main) {
                val updatedNotes = noteAdapter.notes.toMutableList()
                updatedNotes.remove(note)
                noteAdapter.updateNotes(updatedNotes)
                Toast.makeText(this@MainActivity, "笔记已删除", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.toolbar_menu, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.action_add -> {
                showAddNoteDialog()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    private fun showAddNoteDialog() {
        currentImageUri = null
        val dialogLayout = layoutInflater.inflate(R.layout.dialog_add_note, null)
        val titleEditText: EditText = dialogLayout.findViewById(R.id.note_title_edittext)
        val contentEditText: EditText = dialogLayout.findViewById(R.id.note_content_edittext)
        val imagePreview: ImageView = dialogLayout.findViewById(R.id.note_image)
        addImageButton = dialogLayout.findViewById(R.id.add_image_button)
        val buttonCancel: MaterialButton = dialogLayout.findViewById(R.id.button_cancel)
        val buttonAdd: MaterialButton = dialogLayout.findViewById(R.id.button_add)

        addImageButton.setOnClickListener {
            selectImage()
        }

        val builder = AlertDialog.Builder(this)
            .setTitle("添加新笔记")
            .setView(dialogLayout)
            .create()

        buttonCancel.setOnClickListener {
            builder.dismiss()
        }

        buttonAdd.setOnClickListener {
            val title = titleEditText.text.toString().trim()
            val content = contentEditText.text.toString().trim()

            if (title.isNotEmpty()) {
                val newNote = Note(
                    title = title,
                    content = content,
                    imageUri = currentImageUri
                )

                lifecycleScope.launch(Dispatchers.IO) {
                    val noteId = noteDatabase.noteDao().addNote(newNote)

                    withContext(Dispatchers.Main) {
                        val updatedNotes = noteAdapter.notes.toMutableList()
                        updatedNotes.add(newNote)
                        noteAdapter.updateNotes(updatedNotes)
                        Toast.makeText(this@MainActivity, "笔记已添加", Toast.LENGTH_SHORT).show()
                        builder.dismiss()
                    }
                }
            } else {
                Toast.makeText(this, "标题不能为空", Toast.LENGTH_SHORT).show()
            }
        }

        builder.show()
    }

    private fun selectImage() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        intent.type = "image/*"
        startActivityForResult(intent, 100)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 100 && resultCode == RESULT_OK && data != null) {
            val uri = data.data ?: return
            try {
                val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, uri)
                val cacheDir = externalCacheDir ?: return
                val fileName = "note_img_${System.currentTimeMillis()}.jpg"
                val tempFile = File(cacheDir, fileName)
                val outputStream = FileOutputStream(tempFile)
                bitmap.compress(Bitmap.CompressFormat.JPEG, 80, outputStream)
                outputStream.flush()
                outputStream.close()

                currentImageUri = tempFile.absolutePath
                val dialog = findCurrentDialog()
                dialog?.findViewById<ImageView>(R.id.note_image)?.let { imageView ->
                    imageView.visibility = View.VISIBLE
                    Glide.with(this).load(tempFile).centerCrop().into(imageView)
                }
            } catch (e: Exception) {
                e.printStackTrace()
                Toast.makeText(this, "图片处理失败", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun findCurrentDialog(): AlertDialog? {
        val fragmentManager = supportFragmentManager
        for (fragment in fragmentManager.fragments) {
            if (fragment is AlertDialog) {
                return fragment
            }
        }
        return null
    }
}
